{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8721c540",
   "metadata": {},
   "source": [
    "刷新掘金可转债数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e8e0c8a4",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-08-10T23:40:34.882405Z",
     "start_time": "2022-08-10T23:40:11.617611Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:root:JUEJIN: Read index data from server\n",
      "INFO:root:JUEJIN: Read instruments from server\n",
      "INFO:root:JUEJIN: Read bars from server\n",
      "INFO:root:JUEJIN: Read stock price from server\n",
      "INFO:root:Done\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7b6395e25f704d7eb577b02869d7c119"
      },
      "text/plain": [
       "                       datetime order_book_id     open     high      low  \\\n",
       "0     2022-04-07 00:00:00+08:00   SHSE.110038  132.000  133.600  128.210   \n",
       "1     2022-04-08 00:00:00+08:00   SHSE.110038  129.060  130.180  125.460   \n",
       "2     2022-04-11 00:00:00+08:00   SHSE.110038  126.000  127.880  124.520   \n",
       "3     2022-04-12 00:00:00+08:00   SHSE.110038  125.200  127.040  124.400   \n",
       "4     2022-04-13 00:00:00+08:00   SHSE.110038  126.000  126.490  124.240   \n",
       "...                         ...           ...      ...      ...      ...   \n",
       "32995 2022-07-22 00:00:00+08:00   SZSE.128145  164.176  173.200  159.994   \n",
       "32996 2022-07-25 00:00:00+08:00   SZSE.128145  170.800  182.503  162.700   \n",
       "32997 2022-07-26 00:00:00+08:00   SZSE.128145  163.000  163.000  148.696   \n",
       "32998 2022-07-27 00:00:00+08:00   SZSE.128145  152.000  154.312  150.312   \n",
       "32999 2022-07-28 00:00:00+08:00   SZSE.128145  155.000  155.300  152.012   \n",
       "\n",
       "        close    volume  stock_open  stock_close  \n",
       "0      129.06    671870       25.45        25.17  \n",
       "1      126.31    380400       24.88        24.02  \n",
       "2      126.04    381960       23.57        23.81  \n",
       "3      126.82    282610       23.73        24.30  \n",
       "4      124.43    238990       24.21        23.28  \n",
       "...       ...       ...         ...          ...  \n",
       "32995  170.33  20144842         NaN          NaN  \n",
       "32996  163.00  31069834         NaN          NaN  \n",
       "32997  151.90   7554540         NaN          NaN  \n",
       "32998  153.30   4246016         NaN          NaN  \n",
       "32999  153.75   3937696         NaN          NaN  \n",
       "\n",
       "[33000 rows x 9 columns]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from quant.data import juejin\n",
    "import pathlib\n",
    "from importlib import reload\n",
    "reload(juejin)\n",
    "data_dir = pathlib.Path('../../examples/juejin/data').resolve()\n",
    "ins, bars = juejin.refresh_conbond('2022-04-07', None, '1d', data_dir.joinpath('juejin'))\n",
    "logging.info('Done')\n",
    "bars = bars.reset_index()\n",
    "bars"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b8adca2",
   "metadata": {},
   "source": [
    "刷新集思录可转债数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "532713ca",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-06-20T14:39:05.450863Z",
     "start_time": "2022-06-20T14:39:01.765153Z"
    }
   },
   "outputs": [],
   "source": [
    "from quant.data import jisilu\n",
    "import pathlib\n",
    "from importlib import reload\n",
    "import pandas as pd\n",
    "reload(jisilu)\n",
    "data_dir = pathlib.Path('../../examples/juejin/data').resolve()\n",
    "jslins, _ = jisilu.refresh_now(data_dir.joinpath('jisilu'), to_juejin=True)\n",
    "jslins = jslins.reset_index()\n",
    "jslins"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb1b0982",
   "metadata": {},
   "source": [
    "综合掘金和集思录可转债数据（掘金主要提供k线，集思录用于获取指标，如转股溢价率，转股价格等）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51323c68",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-18T15:25:40.358657Z",
     "start_time": "2022-07-18T15:25:38.875538Z"
    }
   },
   "outputs": [],
   "source": [
    "from quant.data import utils, juejin, jisilu\n",
    "import pathlib\n",
    "from importlib import reload\n",
    "reload(juejin)\n",
    "reload(jisilu)\n",
    "reload(utils)\n",
    "data_dir = pathlib.Path('../../examples/juejin/data').resolve()\n",
    "ins, bars = utils.combine_juejin_jsl(data_dir.joinpath('juejin'), data_dir.joinpath('jisilu'),\n",
    "                                   '2022-04-07', '1d')"
   ]
  },
  {
   "cell_type": "raw",
   "id": "5a06a8bd",
   "metadata": {},
   "source": [
    "重新生成集思录数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "edbe9e5a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-19T15:18:43.952949Z",
     "start_time": "2022-07-19T15:18:19.261502Z"
    }
   },
   "outputs": [],
   "source": [
    "from quant.data import jisilu\n",
    "import pathlib\n",
    "from importlib import reload\n",
    "import pandas as pd\n",
    "reload(jisilu)\n",
    "import click\n",
    "\n",
    "data_dir = pathlib.Path('../../examples/juejin/data').resolve()\n",
    "\n",
    "def fix_dt(dt):\n",
    "    for p in ['', 'put-', 'redeem-']:\n",
    "        f = data_dir.joinpath('jisilu', '%s%s.json' % (p, dt))\n",
    "        with f.open(mode='r', encoding='gbk') as fp:\n",
    "            data = json.load(fp)\n",
    "            fp.close()\n",
    "        with f.open(mode='w', encoding='utf-8') as fp:\n",
    "            json.dump(data, fp, ensure_ascii=False, indent=4)\n",
    "            fp.close()\n",
    "dt = '2022-04-07'\n",
    "for dt in get_trading_dates(exchange='SZSE', start_date=dt, end_date='2022-07-19'):\n",
    "    jisilu.refresh_now(data_dir.joinpath('jisilu'), dt=dt)"
   ]
  },
  {
   "cell_type": "raw",
   "id": "3430fa4a",
   "metadata": {},
   "source": [
    "单个转债标的分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b26f126c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-19T00:36:40.168588Z",
     "start_time": "2022-07-19T00:36:39.521000Z"
    }
   },
   "outputs": [],
   "source": [
    "enable_plotly_in_cell()\n",
    "order_book_id='SZSE.123073'\n",
    "cb_bars = bars.loc[pd.IndexSlice[:, order_book_id], :].droplevel(1)\n",
    "cb_bars['cpr_ma'] = cb_bars.convert_premium_rate.rolling(10).mean()\n",
    "f1 = cb_bars[['convert_premium_rate', 'cpr_ma', 'close']].iplot(kind='line', y=['convert_premium_rate', 'cpr_ma'], secondary_y='close', asFigure=True)\n",
    "f1.update_layout(legend=dict(x=0.5, y=1.2))\n",
    "f1.show()\n",
    "\n",
    "stock_bars = history(symbol=ins.loc[order_book_id].stock_code, frequency='1d', start_time=cb_bars.index[0], end_time=cb_bars.index[-1], df=True)\n",
    "\n",
    "df = stock_bars.set_index('eob').rename(columns={'close': 'stock'})[['stock']]\n",
    "df['stock_ma'] = df.stock.rolling(10).mean()\n",
    "f2 = df.join(cb_bars[['close']]).rename(columns={'close': 'cb'}).iplot(kind='line', y=['stock', 'stock_ma'], secondary_y='cb', asFigure=True)\n",
    "f2.update_layout(legend=dict(x=0.5, y=1.2))\n",
    "f2.show()\n",
    "\n",
    "meta = ins.loc[order_book_id:order_book_id]\n",
    "meta = meta.reset_index()\n",
    "meta"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "343d2132",
   "metadata": {},
   "source": [
    "统计过去一段时间，有脉冲行情的转债"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6a8ec16",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-06-17T01:16:52.301128Z",
     "start_time": "2022-06-17T01:16:51.889291Z"
    }
   },
   "outputs": [],
   "source": [
    "bars['spike'] = bars.high / bars.open - 1\n",
    "bars = bars.query('spike > 0.08')\n",
    "# 脉冲因子：规模，转股溢价率，剩余年限\n",
    "data = bars[['spike', 'remaining_size', 'convert_premium_rate']].join(ins[[\n",
    "             'symbol', 'de_listed_date']]).reset_index()\n",
    "data['years_left'] = (data.de_listed_date.dt.date - data.datetime.dt.date).dt.days / 365\n",
    "data['remaining_size'] = data.remaining_size / 100000000\n",
    "df = data.groupby('order_book_id').max('datetime')\n",
    "df = df.reset_index()\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a82a3291",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-31T01:32:46.661921Z",
     "start_time": "2022-05-31T01:32:41.947331Z"
    }
   },
   "outputs": [],
   "source": [
    "from datetime import datetime, timedelta\n",
    "from quant import utils\n",
    "bars = history(symbol=cond._order_book_id, frequency='60s', start_time=cond._state_history[0].datetime, end_time=cond._state_history[-1].datetime.date() + timedelta(days=1), fields='symbol, open, close, low, high, eob', adjust=ADJUST_PREV, df=True)\n",
    "df = bars.set_index('eob')[['open']]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b79e1a1d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-31T08:13:38.309704Z",
     "start_time": "2022-05-31T08:13:24.589275Z"
    }
   },
   "outputs": [],
   "source": [
    "cbs = get_instruments(sec_types=SEC_TYPE_BOND_CONVERTIBLE, df=True)\n",
    "dfmi = dfmi.reset_index()\n",
    "ins = ins.reset_index()\n",
    "ins"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:quant] *",
   "language": "python",
   "name": "conda-env-quant-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
